package com.ymt.bpm.service.platform.config.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.Const.Oplog;
import com.ymt.bpm.model.PBo;
import com.ymt.bpm.service.platform.config.BoService;
import com.ymt.bpm.service.platform.log.OpLogService;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import com.ymt.bpm.util.DhxUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Johnny on 2017/10/23.
 */
@Service
public class BoServiceImpl implements BoService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao mDao;

    @Autowired
    private OpLogService oplog;

    @Override
    public JSONObject query(String tenantId, String appId, String purpose, String search, String sort,
                            String order, int offset, int limit, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("search", search);
        paramMap.put("purpose", purpose);
        paramMap.put("appId", appId);
        paramMap.put("sort", sort);
        paramMap.put("order", order);
        PageHelper.offsetPage(offset, limit);
        List<PBo> list = mDao.selectList(Mapper.PBoMapper, "queryAll", paramMap);
        PageInfo pageInfo = new PageInfo(list);
        JSONObject rtn = new JSONObject();
        JSONArray rows = new JSONArray();
        if (list!=null && list.size()>0) {
            for (PBo bo : list) {
                JSONObject node = DhxUtil.toJsonWithDateAli(bo, Const.LANG_ZH, timezoneOffset);
                node.put("_ITEM_NO", ++offset);
                rows.add(node);
            }
        }
        rtn.put("rows", rows);
        rtn.put("total", pageInfo.getTotal());
        return rtn;
    }

    @Override
    public JSONObject get(String tenantId, String boid, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("boid", boid);
        PBo bo = mDao.selectOne(Mapper.PBoMapper, "selectByPrimaryKey", paramMap);
        JSONObject rtn = DhxUtil.toFastJsonWithDate(bo, lang, timezoneOffset);
        return rtn;
    }

    @Override
    public String checkAttr(String tenantId, String attrName, String value, String boid) {
        if (log.isDebugEnabled()) {
            log.debug("checkAttr tenantId="+tenantId);
            log.debug("checkAttr attrName="+attrName);
            log.debug("checkAttr value="+value);
            log.debug("checkAttr boid="+boid);
        }
        /*if (value!=null && !value.toUpperCase().startsWith("B_")) {
            value = "B_"+value;
        }*/
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("tenantId", tenantId);
        paramMap.put("value", value);
        paramMap.put("boid", boid);
        int rs = mDao.selectOne(Mapper.PBoMapper, "checkAttr"+ StringUtils.capitalize(attrName), paramMap);
        if (log.isDebugEnabled()) {
            log.debug("checkAttr rs="+rs);
        }
        return rs>0 ? "false" : "true";
    }

    /*@Override
    public JSONObject save(String tenantId, String loginName, String displayName, PBo bo) {
        if (tenantId!=null) {
            bo.setTenantId(Integer.parseInt(tenantId));
        }
        int rs = 0;
        if (bo.getBoid()==null || bo.getBoid().length()==0) {
            bo.setBoid("BO-"+ UUID.randomUUID().toString());
            bo.setCreator(loginName);
            bo.setCreatorname(displayName);
            bo.setCreatetime(DateUtil.getGMTDate());
            rs += mDao.insert(Mapper.PBoMapper, "insertSelective", bo);
        } else {
            bo.setChangeuser(loginName);
            bo.setChangeusername(displayName);
            bo.setUpdatetime(DateUtil.getGMTDate());
            rs += mDao.update(Mapper.PBoMapper, "updateByPrimaryKeySelective", bo);
        }
        JSONObject rtn = new JSONObject();
        rtn.put("result", rs);
        return rtn;
    }*/

    @Override
    public JSONObject delete(String tenantId, String loginName, String displayName, String boid) {
        JSONObject rtn = new JSONObject();
        int rs = 0;

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("boid", boid);

        //TODO check reference in bpd
        /*List<Map<String, Object>> refList = mDao.selectList("POrgPosMapper", "selectPosReferedByOrg", paramMap);
        if (refList!=null && refList.size()>0) {
            StringBuilder names = new StringBuilder();
            for (Map<String, Object> map : refList) {
                if (names.length()>0) {
                    names.append(",");
                }
                names.append(map.get("ORG_NAME"));
            }
            rtn.put("referedForms", names);
            return rtn;
        }*/

        PBo bo = mDao.selectOne(Mapper.PBoMapper, "selectByPrimaryKey", boid);

        rs = mDao.delete(Mapper.PBoMapper, "deleteByPrimaryKey", paramMap);
        rtn.put("result", rs);

        //记录日志
        oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.DELETE, Oplog.CODE.BO, bo.getBoname());

        return rtn;
    }

    @Override
    public String getByName(String tenantId, String boname, String lang, int timezoneOffset) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("boname", boname);
        PBo bo = mDao.selectOne(Mapper.PBoMapper, "selectByBoname", paramMap);
        if (log.isDebugEnabled()) {
            log.debug("getByName bo="+bo);
        }
        JSONObject attrs = JSONObject.parseObject(bo.getAttrs());//turn string to object
        JSONObject bojo = DhxUtil.toJsonWithDate(bo, lang, timezoneOffset);
        bojo.put("attrs", attrs);
        return bojo.toString();
    }

    @Override
    public String save(String tenantId, String boStr, String loginName, String displayName, String lang) {
        JSONObject boJo = JSONObject.parseObject(boStr);
        String boid = boJo.getString("boid");
        if (boid==null || boid.length()==0) {
            PBo bo = new PBo();
            boid = "BO-"+UUID.randomUUID().toString();
            if (tenantId!=null) {
                bo.setTenantId(Integer.parseInt(tenantId));
            }
            bo.setBoid(boid);
            bo.setBoname(boJo.getString("boname"));
            String bodesc = boJo.getString("bodesc");
            if (bodesc!=null && bodesc.length()>0) {
                bo.setBodesc(bodesc);
            }
            bo.setPurpose(boJo.getString("purpose"));
            bo.setCreator(loginName);
            bo.setCreatorname(displayName);
            bo.setChangeuser(loginName);
            bo.setChangeusername(displayName);
            bo.setCreatetime(DateUtil.getGMTDate());
            bo.setUpdatetime(DateUtil.getGMTDate());
            bo.setAttrs(boJo.getJSONObject("attrs").toString());
            mDao.insert(Mapper.PBoMapper, "insert", bo);

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.CREATE, Oplog.CODE.BO, bo.getBoname());
        } else {
            PBo bo = mDao.selectOne(Mapper.PBoMapper, "selectByPrimaryKey", boid);
            String boname = boJo.getString("boname");
            if (boname!=null && boname.length()>0) {
                bo.setBoname(boname);
            }
            String bodesc = boJo.getString("bodesc");
            if (bodesc!=null && bodesc.length()>0) {
                bo.setBodesc(bodesc);
            }
            bo.setPurpose(boJo.getString("purpose"));
            bo.setChangeuser(loginName);
            bo.setChangeusername(displayName);
            bo.setUpdatetime(DateUtil.getGMTDate());
            JSONObject attrs = boJo.getJSONObject("attrs");
            if (attrs!=null) {
                bo.setAttrs(attrs.toString());
            }
            mDao.update(Mapper.PBoMapper, "updateByPrimaryKeySelective", bo);
            boid = bo.getBoid();

            //记录日志
            oplog.bizlog(tenantId, loginName, displayName, null, Oplog.OP.UPDATE, Oplog.CODE.BO, bo.getBoname());
        }
        return boid;
    }
}
